﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PartsRetrospect.Comm
{
    public class ClsGzip
    {
        public void CompressFile(string sourceFile, string destinationFile)
        {
            //'压缩档案
            if (!File.Exists(sourceFile)) return;

            FileStream sourceStream = null;
            FileStream destinationStream = null;
            GZipStream compressedStream = null;
            try
            {

                //'Read the bytes from the source file into a byte array
                sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                //'Read the source stream values into the buffer
                Byte[] buffer = new byte[sourceStream.Length - 1];
                //Dim buffer(sourceStream.Length -1) As Byte
                int checkCounter = sourceStream.Read(buffer, 0, buffer.Length);

                if (checkCounter != buffer.Length) return;

                //'Open the FileStream to write to
                destinationStream = new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write);

                //'Create a compression stream pointing to the destiantion stream
                compressedStream = new GZipStream(destinationStream, CompressionLevel.NoCompression);

                //'Now write the compressed data to the destination file
                compressedStream.Write(buffer, 0, buffer.Length);
            }
            catch (Exception)
            {
            }
            finally
            {
                if (sourceStream != null) sourceStream.Close();
                if (compressedStream != null) compressedStream.Close();
                if (destinationStream != null) destinationStream.Close();
            }
        }
    }
}
